
// 数据库对象的基本类
class Common {
  constructor () {}
  
  // 根据schema初始化对象
  initBySchema (schema = {}) {
    this._schema = schema
    for (let key in schema) {
      this[key] = schema[key].default
    }
  }
  
  // 将对象按照schema，更新本类
  setData (data = {}) {
    const schema = this._schema
    for (let key in schema) {
      if (data.hasOwnProperty(key)) {
        // 本身具有key
        this[key] = data[key]
        continue
      }
      // 没有key，则检查数据库key
      const dbKey = schema[key].dbKey
      if (dbKey && data.hasOwnProperty(dbKey)) {
        this[key] = data[dbKey]
      }
    }
  }
  
  // 将data中的数据转为数据库需要的字段
  toDbData (data = {}) {
    const schema = this._schema
    let res = {}
    
    let keyList = []
    let dbKeyList = []
    for (let key in schema) {
      keyList.push(key)
      dbKeyList.push(schema[key].dbKey)
    }
    
    for (let key in data) {
      const dbIndex = dbKeyList.indexOf(key)
      if (dbIndex >= 0) {
        res[key] = data[key]
        continue
      }
      const keyIndex = keyList.indexOf(key)
      if (keyIndex >= 0) {
        const dbKey = dbKeyList[keyIndex]
        if (dbKey) {
          res[dbKeyList[keyIndex]] = data[key]
        }
        else {
          res[key] = data[key]
        }
      }
    }
    return res
  }
}

export default Common